package movilmax.sia_corp.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.interceptor.SessionAware;

import movilmax.sia_corp.model.Customer;
import movilmax.sia_corp.model.CustomerDAO;
import movilmax.sia_corp.model.Usuario;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage(value = "showcase")
public class JsonTable extends ActionSupport implements SessionAware {

  private static final long   serialVersionUID = 5078264277068533593L;
  private static final Log    log              = LogFactory.getLog(JsonTable.class);

  private List<Customer>      gridModel;
  private List<Customer>      myCustomers;
  private Integer             rows             = 0;
  private Integer             page             = 0;
  private Integer             total            = 0;
  private Integer             record           = 0;
  private String              sord;
  private String              sidx;
  private String              searchField;
  private String              searchString;
  private String              searchOper;
  private boolean             loadonce         = false;
  private Map<String, Object> session;
  
  private int opc;
  private String ids;
  private String xxids;

  /*
@Actions( {
    @Action(value = "/jsontable", results = {
      @Result(name = "success", type = "json")
    })
  })
  */
  
  @SuppressWarnings({ "rawtypes", "unused" })
public String execute(){
	 // Debug.println("IDX", this.getIds()  );
	//  Debug.println("OPC"," "+ this.getOpc()  );
    log.debug("Pagina " + getPage()+" Filas " + getRows() +" Ordenar Por "+ getSord()+" Index Row :" + getSidx());
    log.debug("Buscar :" + searchField + " " + searchOper + " " + searchString);
    Map sessionx = ActionContext.getContext().getSession();
	Usuario USUARIO = (Usuario)sessionx.get("ses_usuario");	 
	Object list = (Object)session.get("mylist");
	//if(list==null){
	//	  Debug.println("LISTA", "nula");
	//}else{
	//	  Debug.println("LISTA", "no nula="+list.toString() ); 
	//}
    
    
    //Object list = session.get("mylist");
	
	    //if (list != null){
	    //	Debug.println("LISTA", "recargar");
	        //myCustomers = (List<Customer>) list;
	   // }else{
	    //	Debug.println("LISTA", "cargar");
	    //	this.setSord("x");
	   // }
    	//Debug.println("LISTA", "cargar");
        log.debug("Cargar...");
        String SQL="";
        switch(getOpc()){
           case 1:
        	   if( USUARIO.getUsuario().equals("yenny.faria") || USUARIO.getUsuario().equals("dick") || USUARIO.getUsuario().equals("adm") || USUARIO.getUsuario().equals("pcorp")  ){
        		   SQL="Select S.cod as id,A.descripcion as des_actividad,D.descripcion as des_detalle,S.obs,S.stx,S.hora,CONVERT(varchar(30),S.fecha,103) as fecha,S.usuario from corp_seguimiento_actividades S,corp_actividades A,corp_detalles_actividad D "+
		               "where S.prospecto='"+ this.getIds()+"' and S.actividad=A.cod and S.detalle=D.cod and S.mostrar='1' Order by S.cod DESC";  
        	   }else{
        	      SQL="Select S.cod as id,A.descripcion as des_actividad,D.descripcion as des_detalle,S.obs,S.stx,S.hora,CONVERT(varchar(30),S.fecha,103) as fecha,S.usuario from corp_seguimiento_actividades S,corp_actividades A,corp_detalles_actividad D "+
		               "where  S.prospecto='"+ this.getIds()+"' and S.actividad=A.cod and S.detalle=D.cod and S.mostrar='1' and D.ver='1' Order by S.cod DESC";
        	   } 
        	   this.setSord("x");
    	   break;
           case 2:
        	  // SQL="Select S.cod as id,A.descripcion as des_actividad,D.descripcion as des_detalle,S.obs,S.stx,S.hora,CONVERT(varchar(30),S.fecha,103) as fecha,S.usuario from corp_seguimiento_actividad_cli S,corp_actividades A,corp_detalles_actividad D "+
              // "where S.cliente='"+ this.getIds()+"' and S.actividad=A.cod and S.detalle=D.cod and S.mostrar='1'  Order by S.cod DESC";
        	     SQL = "select A.codigo as id, A.codigo,CONVERT(varchar(30),A.fecha,103) as fecha,A.hora,A.obs_operador,A.obs_cliente, " +
        		       "T.descripcion as des_actividad,X.descripcion as des_detalle,   "+
        		       "U.descripcion as usuario,A.area,D.descripcion as area_usuario  "+
        		       "from actividades A,tipos_actividad T,tipos_actividad_det X,usuarios U,departamentos D,contratos C " +
        		       "where C.cliente='" + this.getIds()+ "' and C.contrato=A.contrato and A.tipo=T.cod and A.tipo_det=X.cod "+
        		       "and A.usuario=U.usuario and U.departamento=D.cod " +
        		       "Order by A.fecha DESC,A.hora DESC " ;
        	   this.setSord("x");
           break;
       }  
     myCustomers = CustomerDAO.cargar(getOpc(),SQL);
    //}
    if (getSord() != null && getSord().equalsIgnoreCase("asc"))
    {
      Collections.sort(myCustomers);
    }
    if (getSord() != null && getSord().equalsIgnoreCase("desc"))
    {
      Collections.sort(myCustomers);
      Collections.reverse(myCustomers);
    }

    setRecord(CustomerDAO.getCustomersCount(myCustomers));

    int to = (getRows() * getPage());
    int from = to - getRows();

    if (to > getRecord()) to = getRecord();

    if (loadonce)
    {
      setGridModel(myCustomers);
    }
    else
    {
      if (searchString != null && searchOper != null)
      {
        int id = Integer.parseInt(searchString);
        if (searchOper.equalsIgnoreCase("eq"))
        {
          log.debug("search id equals " + id);
          List<Customer> cList = new ArrayList<Customer>();
          cList.add(CustomerDAO.findById(myCustomers, id));
          setGridModel(cList);
        }
        else if (searchOper.equalsIgnoreCase("ne"))
        {
          log.debug("search id not " + id);
          setGridModel(CustomerDAO.findNotById(myCustomers, id, from, to));
        }
        else if (searchOper.equalsIgnoreCase("lt"))
        {
          log.debug("search id lesser then " + id);
          setGridModel(CustomerDAO.findLesserAsId(myCustomers, id, from, to));
        }
        else if (searchOper.equalsIgnoreCase("gt"))
        {
          log.debug("search id greater then " + id);
          setGridModel(CustomerDAO.findGreaterAsId(myCustomers, id, from, to));
        }
      }
      else
      {
        setGridModel(CustomerDAO.getCustomers(myCustomers, from, to));
      }
    }

    setTotal((int) Math.ceil((double) getRecord() / (double) getRows()));

    session.put("mylist", myCustomers);

    return SUCCESS;
  }

  public String getJSON()
  {
    return execute();
  }

  /**
   * @return how many rows we want to have into the grid
   */
  public Integer getRows()
  {
    return rows;
  }

  /**
   * @param rows
   *          how many rows we want to have into the grid
   */
  public void setRows(Integer rows)
  {
    this.rows = rows;
  }

  /**
   * @return current page of the query
   */
  public Integer getPage()
  {
    return page;
  }

  /**
   * @param page
   *          current page of the query
   */
  public void setPage(Integer page)
  {
    this.page = page;
  }

  /**
   * @return total pages for the query
   */
  public Integer getTotal()
  {
    return total;
  }

  /**
   * @param total
   *          total pages for the query
   */
  public void setTotal(Integer total)
  {
    this.total = total;
  }

  /**
   * @return total number of records for the query. e.g. select count(*) from
   *         table
   */
  public Integer getRecord()
  {
    return record;
  }

  /**
   * @param record
   *          total number of records for the query. e.g. select count(*) from
   *          table
   */
  public void setRecord(Integer record)
  {

    this.record = record;

    if (this.record > 0 && this.rows > 0)
    {
      this.total = (int) Math.ceil((double) this.record / (double) this.rows);
    }
    else
    {
      this.total = 0;
    }
  }

  /**
   * @return an collection that contains the actual data
   */
  public List<Customer> getGridModel()
  {
    return gridModel;
  }

  /**
   * @param gridModel
   *          an collection that contains the actual data
   */
  public void setGridModel(List<Customer> gridModel)
  {
    this.gridModel = gridModel;
  }

  /**
   * @return sorting order
   */
  public String getSord()
  {
    return sord;
  }

  /**
   * @param sord
   *          sorting order
   */
  public void setSord(String sord)
  {
    this.sord = sord;
  }

  /**
   * @return get index row - i.e. user click to sort.
   */
  public String getSidx()
  {
    return sidx;
  }

  /**
   * @param sidx
   *          get index row - i.e. user click to sort.
   */
  public void setSidx(String sidx)
  {
    this.sidx = sidx;
  }

  public void setSearchField(String searchField)
  {
    this.searchField = searchField;
  }

  public void setSearchString(String searchString)
  {
    this.searchString = searchString;
  }

  public void setSearchOper(String searchOper)
  {
    this.searchOper = searchOper;
  }

  public void setLoadonce(boolean loadonce)
  {
    this.loadonce = loadonce;
  }

  public void setSession(Map<String, Object> session)
  {
    this.session = session;
  }
  /* determinar el reporte que se va ejecutar*/
	public int getOpc() {
		return opc;
	}
	
	public void setOpc(int opc) {
		this.opc = opc;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getXxids() {
		return xxids;
	}

	public void setXxids(String xxids) {
		this.xxids = xxids;
	}

   
   
	
}